import { v4 as uuidv4, v1 as uuidv1 } from 'uuid';

/**
 * Generate a UUID v4 (random)
 */
export const generateUUID = (): string => {
  return uuidv4();
};

/**
 * Generate a UUID v1 (timestamp-based)
 */
export const generateTimeBasedUUID = (): string => {
  return uuidv1();
};

/**
 * Generate a short UUID (8 characters)
 */
export const generateShortUUID = (): string => {
  return uuidv4().substring(0, 8);
};

/**
 * Generate a correlation ID for message tracking
 */
export const generateCorrelationId = (): string => {
  return `corr_${Date.now()}_${generateShortUUID()}`;
};

/**
 * Generate a trace ID for distributed tracing
 */
export const generateTraceId = (): string => {
  return `trace_${generateUUID()}`;
};

/**
 * Generate a span ID for distributed tracing
 */
export const generateSpanId = (): string => {
  return `span_${generateShortUUID()}`;
};

/**
 * Validate if a string is a valid UUID
 */
export const isValidUUID = (uuid: string): boolean => {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(uuid);
};

/**
 * Extract timestamp from UUID v1
 */
export const extractTimestampFromUUIDv1 = (uuid: string): Date | null => {
  if (!isValidUUID(uuid)) {
    return null;
  }

  try {
    // UUID v1 timestamp extraction logic
    const hex = uuid.replace(/-/g, '');
    const timeLow = parseInt(hex.substring(0, 8), 16);
    const timeMid = parseInt(hex.substring(8, 12), 16);
    const timeHigh = parseInt(hex.substring(12, 16), 16) & 0x0fff;

    const timestamp = (timeHigh << 32) | (timeMid << 16) | timeLow;
    const unixTimestamp = (timestamp - 0x01b21dd213814000) / 10000;

    return new Date(unixTimestamp);
  } catch {
    return null;
  }
};
